//
//  RJHomeBottomFatherView.m
//  AirQuality
//
//  Created by Po on 15/3/16.
//  Copyright (c) 2015年 Po. All rights reserved.
//

#import "RJHomeBottomFatherView.h"
#import "RJCheckDataFitCell.h"
#import "RJUserData.h"


@interface RJHomeBottomFatherView () <UITableViewDelegate, UITableViewDataSource>

@property (retain, nonatomic) UIButton * detailButton;              //详情按钮
@property (retain, nonatomic) UIButton * backButton;                //返回按钮
@property (retain, nonatomic) UIView * backAlpha;                   //饼图背景
@property (retain, nonatomic) UIImageView * backImage;              //表格背景

@property (retain, nonatomic) NSArray * offLines;                   //离线数据
@property (assign, nonatomic) NSUInteger buttonNum;                 //按钮个数


@property (assign, nonatomic) BOOL isShowDetail;                    //是否展示详细信息

@end

@implementation RJHomeBottomFatherView

- (instancetype)initWithFrame:(CGRect)frame
{
    _viewRect = frame;
    _viewRect.size.width = ScreenWidth;
    _isLoadingShow = NO;
    _isConnecting = NO;
    _isShowDetail = NO;
    self = [super initWithFrame:frame];
    if (self) {
        [self addSubview:[self getPieContentView]];
        [self addSubview:[self getTableContentView]];
        UISwipeGestureRecognizer * leftPan = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(moveLeft)];
        leftPan.direction = UISwipeGestureRecognizerDirectionLeft;
        UISwipeGestureRecognizer * rightPan = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(moveRight)];
        rightPan.direction = UISwipeGestureRecognizerDirectionRight;
        [self addGestureRecognizer:leftPan];
        [self addGestureRecognizer:rightPan];
    }
    return self;
}

#pragma mark - getter
- (UIView *)getPieContentView
{
    if (!_pieContentView) {
        CGRect rect = self.bounds;
        rect.origin.x = 10;
        rect.size.width -= 20;
        rect.origin.y += 10;
        rect.size.height -= 40;
        _pieContentView = [[UIView alloc] initWithFrame:rect];
        [_pieContentView.layer setCornerRadius:5];

    }
    return _pieContentView;
}

- (UIView *)getTableContentView
{
    if (!_tableContentView) {
        CGRect rect = self.bounds;
        rect.origin.x += ScreenWidth;
        rect.size.width -= 20;
        rect.origin.y += 10;
        rect.size.height -= 40;
        _tableContentView = [[UIView alloc] initWithFrame:rect];
        
        [_tableContentView.layer setCornerRadius:5];
        _tableContentView.layer.shadowColor = [UIColor blackColor].CGColor;
        _tableContentView.layer.shadowOffset = CGSizeMake(0,1);
        _tableContentView.layer.shadowOpacity = 0.6;
        _tableContentView.layer.shadowRadius = 1.0;
    }
    return _tableContentView;
}

- (RJPieCartView *)getPieView:(CGRect)rect title:(NSString *)title
{
    if (!_pieView) {
        CGRect pieRect = rect;
        pieRect.origin.x += 15;
        pieRect.size.width -= 30;
        pieRect.origin.y += 15;
        pieRect.size.height -= 60;
        _pieView = [[RJPieCartView alloc] initWithFrame:pieRect];
//        [_pieView setBackgroundColor:[UIColor clearColor]];
        [_pieView.layer setCornerRadius:5];
        [_pieView.layer setMasksToBounds:YES];
        [self.pieContentView addSubview:[self getTitleLabel:title]];
        
    }
    return _pieView;
}

- (UITableView *)getTableView:(CGRect)rect
{
    if (!_tableView) {
        rect.size.height -= 40;
        _tableView = [[UITableView alloc] initWithFrame:rect style:UITableViewStylePlain];
        [_tableView setDataSource:self];
        [_tableView setDelegate:self];
        [_tableView setBackgroundColor:[UIColor clearColor]];
        [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    }
    return _tableView;
}

- (UIImageView *)getImageViewWithFrame:(CGRect)frame imageName:(NSString *)image
{
    /**homeBottomTableSection*/
    UIImageView * imageView = [[UIImageView alloc] initWithFrame:frame];
    [imageView setImage:[UIImage imageNamed:image]];
    return imageView;
}

- (UIImageView *)getNoDataImageView
{
    UIImageView * imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
    [imageView setImage:[UIImage imageNamed:@"NoData"]];
    CGPoint center = self.center;
    center.y += 50;
    [imageView setCenter:center];
    return imageView;
}

- (void)getOfflinesData
{
    if ([RJUserData defaultRJUserData].isProvince) {
        _offLines = [self getAllOffLineStaionDataWithData:_detailData];
    } else {
        _offLines = _detailData;
    }
    if (_type == HomeBottomTableAQI) {
        _buttonNum = 1;
    } else {
        _buttonNum = 2;
    }
    //离线数据是否为空
    if ([_offLines count] == 0) {
        [self addSubview:[self getNoDataImageView]];
    }
}

- (void)showPieViewButton
{
    CGRect rect = _pieView.frame;
    rect.origin.x = _pieView.frame.size.width - 180;
    rect.size.width = 200;
    rect.origin.y = rect.size.height + 15;
    rect.size.height = 30;
    self.pieContentView.userInteractionEnabled = YES;
    [self.pieContentView addSubview:[self getDetailButton:rect]];
}

- (UIButton *)getDetailButton:(CGRect)rect
{
    if (!_detailButton) {
        _detailButton = [[UIButton alloc] initWithFrame:rect];
        [_detailButton addTarget:self action:@selector(pressDetailButton:) forControlEvents:UIControlEventTouchUpInside];
        [_detailButton setTitle:@"点击查看离线站点详情 >>>" forState:UIControlStateNormal];
        [_detailButton setTitleColor:SysMainColor forState:UIControlStateNormal];
        [_detailButton setBackgroundColor:[UIColor whiteColor]];
        [_detailButton.titleLabel setFont:[UIFont systemFontOfSize:14]];
        [_detailButton.layer setCornerRadius:5];
    }
    return _detailButton;
}

- (UIButton *)getBackButton:(CGRect)rect
{
    if (!_backButton) {
        _backButton = [[UIButton alloc] initWithFrame:rect];
        [_backButton addTarget:self action:@selector(pressDetailButton:) forControlEvents:UIControlEventTouchUpInside];
        [_backButton setTitle:@"返回 <<<" forState:UIControlStateNormal];
        [_backButton setTitleColor:SysMainColor forState:UIControlStateNormal];
        [_backButton setBackgroundColor:[UIColor whiteColor]];
        [_backButton.titleLabel setFont:[UIFont systemFontOfSize:14]];
        [_backButton.layer setCornerRadius:5];
    }
    return _backButton;
}

- (UILabel *)getTitleLabel:(NSString *)title
{
    if (!_pieTitleLabel) {
        _pieTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(2, 0, self.frame.size.width / 5 * 3, (DeviceType <= 5.5) ? 30 : 40)];
        [_pieTitleLabel setBackgroundColor:SysMainColor];
        [_pieTitleLabel setTextColor:[UIColor whiteColor]];
        [_pieTitleLabel setTextAlignment:NSTextAlignmentCenter];
        [_pieTitleLabel setText:title];
        UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:_pieTitleLabel.bounds byRoundingCorners:UIRectCornerTopLeft| UIRectCornerBottomRight cornerRadii:CGSizeMake(5, 5)];
        CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
        maskLayer.frame = _pieTitleLabel.bounds;
        maskLayer.path = maskPath.CGPath;
        _pieTitleLabel.layer.mask = maskLayer;
    }
    return _pieTitleLabel;
}

#pragma mark - event
- (void)pressDetailButton:(UIButton *)sender
{
    
    if (_offLine == 0) {
        [RJTools showMsg:@"暂无离线站点" time:1.5];
        return;
    }
    
    sender.selected = !sender.selected;

    if (!_isShowDetail) {
        [self getOfflinesData];
        CGRect rect = _tableContentView.bounds;
        if (!_backImage) {
            _backImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, rect.size.width, rect.size.height)];
            [_backImage setImage:GetImage((_type == HomeBottomTableCity ? @"connectCityBack.png":@"connectContryBack.png"))];
            [_tableContentView addSubview:_backImage];
        }

        [self.tableContentView addSubview:[self getTableView:rect]];
        
        [self.tableContentView addSubview:[self getBackButton:CGRectMake(rect.size.width - 90, rect.size.height - 40, 80, 30)]];
        [UIView animateWithDuration:0.5 animations:^{
            CGRect pieRect = _pieContentView.frame;
            [_tableContentView setFrame:pieRect];
            
            CGRect tempRect = _pieView.frame;
            tempRect.origin.x -= ScreenWidth;
            [_pieContentView setFrame:tempRect];
        } completion:^(BOOL finished) {
            [_pieContentView setHidden:YES];
        }];
    } else {
        CGRect rect = self.frame;
        rect.origin.x += ScreenWidth;
        [_pieContentView setHidden:NO];
        [UIView animateWithDuration:0.5 animations:^{
            CGRect tableRect = _tableContentView.frame;
            [_pieContentView setFrame:tableRect];
            
            CGRect tempRect = _pieView.frame;
            tempRect.origin.x += ScreenWidth;
            [_tableContentView setFrame:tempRect];
        } completion:^(BOOL finished) {
            [_tableView removeFromSuperview];
        }];
    }
    
    _isShowDetail = !_isShowDetail;
    
}

- (void)netFinish:(NetRequestStatus)status
{
    if (_moveDelegate && [_moveDelegate respondsToSelector:@selector(HomeBottomFatherView:netFinish:)]) {
        [_moveDelegate HomeBottomFatherView:self netFinish:status];
    }
}

#pragma mark - delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_offLines count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (_type == HomeBottomTableAQI) {
        return 0;
    }
    return 40;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth - 20, 40)];
    [view setBackgroundColor:SysMainColor];
    
    RJCheckDataFitCell * cell = [[RJCheckDataFitCell alloc] initWithFrame:view.bounds buttonNum:_buttonNum];
    [cell setAllEfficacy:NO];
    cell.backgroundColor = [UIColor clearColor];
    cell.contentView.backgroundColor = [UIColor clearColor];
    cell.selectedBackgroundView = [[UIView alloc] init];
    [cell setAllFont:[UIFont systemFontOfSize:20]];
    [cell setLineColor:SysMainColor];
    NSArray * imageArray = (_type == HomeBottomTableAQI ? @[@"homeTableCity"]:@[@"homeTablePosition",@"homeTableCity"]);;
    NSArray * titleArray = (_type == HomeBottomTableAQI ? @[@"离线城市"]:@[@"离线站点",@"所属城市"]);
    for (NSUInteger i = 0; i < _buttonNum; i ++) {
        RJCheckDataCellButton * button = cell.allButtons[i];
        [button setTitle:titleArray[i] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [button setImage:[UIImage imageNamed:imageArray[i]] forState:UIControlStateNormal];
    }
    [view addSubview:cell];
    return view;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * cellIdent = @"HomeBottomCell";
    RJCheckDataFitCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdent];
    if (!cell) {
        cell = [[RJCheckDataFitCell alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth -15, 25) buttonNum:_buttonNum];
        [cell setAllEfficacy:NO];
        cell.backgroundColor = [UIColor clearColor];
        cell.contentView.backgroundColor = [UIColor clearColor];
        cell.selectedBackgroundView = [[UIView alloc] init];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell setAllFont:[UIFont systemFontOfSize:16]];
        if (indexPath.row != ([_offLines count] - 1)) {
            [cell setLineColor:SysMainColor];
            [cell showLine];
        }
    }
    if (_type != HomeBottomTableAQI) {
        RJCheckDataCellButton * cityButton = cell.allButtons[1];
        [cityButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        NSString *cityName;
        if ([RJUserData defaultRJUserData].isProvince) {
             cityName = [[_offLines[indexPath.row] allKeys] lastObject];
        }else{
           cityName = _offLines[indexPath.row];
        }
        [cityButton setTitle:cityName forState:UIControlStateNormal];
        RJCheckDataCellButton * positionButton = cell.allButtons[0];
        [positionButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        NSString * positionName;
        if ([RJUserData defaultRJUserData].isProvince) {
            positionName = [[[_offLines[indexPath.row] allObjects] lastObject] lastObject];
        }else{
            positionName = _offLines[indexPath.row];
        }
        [positionButton setTitle:positionName forState:UIControlStateNormal];
    } else {
        RJCheckDataCellButton * positionButton = cell.allButtons[0];
        [positionButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        NSString * positionName = _offLines[indexPath.row];
        [positionButton setTitle:positionName forState:UIControlStateNormal];
    }
    return cell;
}

#pragma mark - function
- (NSArray *)getAllOffLineStaionDataWithData:(NSArray *)data
{
    if (_type == HomeBottomTableAQI) {
        return data;
    }
    NSMutableArray * offLineArray = [[NSMutableArray alloc] init];
    NSMutableArray * stationsArray = [[NSMutableArray alloc] init];
    for (NSDictionary * dic in data) {
        if ([dic[@"OFFLINE"] integerValue] == 0) {
            continue;
        }
        if (_type != HomeBottomTableAQI) {
            NSArray * stations;
            if (_type == HomeBottomTableCity) {
                stations = [dic[@"OFFLINESTATION"] componentsSeparatedByString:@","];
            } else {
                stations = @[dic[@"STATIONNAME"]];
            }
            for (NSString * cityName in stations) {
                [offLineArray addObject:@{dic[@"CITYNAME"]:@[cityName]}];
            }
        } else {
            [stationsArray addObject:dic[@"STATIONNAME"]];
        }
    }
    if (_type == HomeBottomTableAQI) {
        return stationsArray;
    }
    return offLineArray;
}

- (void)showLoadingView
{
    if (!_isLoadingShow && _isConnecting) {
        _isLoadingShow = YES;
//        self.loadView = [[RJLoadView alloc] initWithFrame:self.viewRect];
//        [self addSubview:self.loadView];
        [MBProgressHUD showMessage:@"正在加载..."];
    }
}
- (void)freeLoadingView
{
    self.isConnecting = NO;
    if (_isLoadingShow) {
//        [self.loadView removeFromSuperview];
//        self.loadView = nil;
//        _isLoadingShow = NO;
        [MBProgressHUD hideHUD];
    }
}

- (void)setData:(NSArray *)data
{
    if (_delegate) {
        [_delegate setData:data];
    }
}

- (void)freeData
{
    if (_delegate) {
        [_delegate freeData];
    }
}

- (void)moveLeft
{
    if (_moveDelegate) {
        [_moveDelegate touchMove:YES];
    }
}

- (void)moveRight
{
    if (_moveDelegate) {
        [_moveDelegate touchMove:NO];
    }
}
@end
